package XishiBackend.controllers.microsite;

import java.io.UnsupportedEncodingException;
import java.util.*;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import XishiBackend.base.Constant;
import XishiBackend.base.Encrypt;
import XishiBackend.base.Json;
import XishiBackend.base.Message;
import XishiBackend.base.Web;
import XishiBackend.models.entity.Distribution;
import XishiBackend.models.entity.User;
import XishiBackend.models.entity.Voucher;
import XishiBackend.services.microsite.MicrositeUserService;

@RestController
@EnableAutoConfiguration
@RequestMapping("/microsite/user")
public class MicrositeUserController {
    @Autowired
    private MicrositeUserService uS;
    
    @RequestMapping(value = "/userinfo",method=RequestMethod.POST)
    public String userinfo(@RequestParam("sig") String sig,@RequestParam("code") String code) {
        //根据CODE获取openId
        String url = Constant.W_USER_ACCESS_TOKEN_URL+"?appid="+Constant.W_APP_ID+"&secret="+Constant.W_APP_SECRET+"&code="+code+"&grant_type=authorization_code";
        System.out.println("userinfo:"+url);
        JSONObject json = JSONObject.fromObject(Web.sendGet(url));
        if(json.containsKey("errcode") && json.getInt("errcode") != 0) {
            return Json.format(1, "获取用户信息失败，"+json.getString("errmsg"));
        }
        
        User u = uS.findUserByOpenId(json.getString("openid"));
        return Json.format(0, "获取用户信息成功", u);
    }
    
    @RequestMapping(value = "/getjsapiconfig", method = RequestMethod.POST)
    public String getjsapiconfig(@RequestParam("sig") String sig, @RequestParam("url") String url) throws UnsupportedEncodingException {
        url = java.net.URLDecoder.decode(url, "utf-8");
        long timestamp = new Date().getTime()/1000;
        String nonceStr = Constant.wxRandomString();
        nonceStr = nonceStr.substring(0, 16);
        String signature = Constant.wxJsSign(timestamp, nonceStr, url);
        if(signature == null) {
            return Json.format(1, "获取jsapi配置失败，获取签名失败");
        }
        Map<String,Object> r = new HashMap<String,Object>();
        r.put("appId", Constant.W_APP_ID);
        r.put("timestamp", timestamp);
        r.put("nonceStr", nonceStr);
        r.put("signature", Encrypt.SHA1(signature));
        r.put("str", signature);
        return Json.format(0, "获取jsapi配置成功", r);
    }
    
    @RequestMapping(value = "/alldistribution", method=RequestMethod.POST)
    public String alldistribution(@RequestParam("sig") String sig) {
        List<Map<String, Object>> dList = uS.findAllDistribution();
        return Json.format(0, "获取取餐点列表成功", dList);
    }
    
    @RequestMapping(value = "/changedistribution",method=RequestMethod.POST)
    public String changedistribution(@RequestParam("sig") String sig,@RequestParam("userId") long userId, @RequestParam("distributionId") long distributionId) {
        User u = uS.findUserById(userId);
        if(u == null) {
            return Json.format(1, "修改取餐点失败，用户不存在");
        }
        Distribution d = uS.findDistributionById(distributionId);
        if(d == null) {
            return Json.format(2, "修改取餐点失败，取餐点不存在");
        }
        
        u.setDistributionId(distributionId);
        if(uS.save(u)) {
            return Json.format(0, "修改取餐点成功");
        }
        else {
            return Json.format(3, "修改取餐点失败，用户保存失败");
        }
    }
    
    @RequestMapping(value = "/sendvalidatecode",method=RequestMethod.POST)
    public String sendvalidatecode(@RequestParam("sig") String sig,@RequestParam("userId") long userId, @RequestParam("tel") String tel) {
        User u = uS.findUserById(userId);
        if(u == null) {
            return Json.format(1, "发送验证码失败，用户不存在");
        }
        //生成验证码，并发送
        String validateCode = Constant.generateRandomCode(6);
        if(!Message.sendValidateCode(tel, validateCode)) {
            return Json.format(3, "发送验证码失败，无法发法");
        }
        //将生成的验证码存到数据库，并指定过期时间
        u.setValidateCode(validateCode);
        Date now = new Date();
        u.setExpireTime(now.getTime()/1000+2*3600);
        if(uS.save(u)) {
            return Json.format(0, "发送验证码成功");
        }
        else {
            return Json.format(2, "发送验证码失败，修改用户失败");
        }
    }
    
    @RequestMapping(value = "/updatetel",method=RequestMethod.POST)
    public String updatetel(@RequestParam("sig") String sig,@RequestParam("userId") long userId, @RequestParam("tel") String tel, 
            @RequestParam("validateCode") String validateCode) {
        User u = uS.findUserById(userId);
        if(u == null) {
            return Json.format(1, "修改手机号失败，用户不存在");
        }
        //验证验证码的有效性
        Date now = new Date();
        if(!u.getValidateCode().equals(validateCode) || u.getExpireTime() < now.getTime()/1000) {
            return Json.format(2, "修改手机号失败，验证码错误或过期");
        }
        //修改手机号
        u.setTel(tel);
        if(uS.save(u)) {
            return Json.format(0, "修改手机号成功");
        }
        else {
            return Json.format(3, "修改手机号失败，修改用户失败");
        }
    }
    
    @RequestMapping(value = "/voucherstatus",method=RequestMethod.POST) 
    public String voucherstatus(@RequestParam("sig") String sig) {
        Map<String,String> vsmap = new HashMap<String,String>();
        for(int i = 0;i < Constant.VOUCHER_STATUS.length;i++) {
            vsmap.put("" + i, Constant.VOUCHER_STATUS[i]);
        }
        return Json.format(0, "获取优惠券状态列表成功", vsmap);
    }
    
    @RequestMapping(value = "/allvoucher",method=RequestMethod.POST) 
    public String allvoucher(@RequestParam("sig") String sig,@RequestParam("userId") long userId) {
        User u = uS.findUserById(userId);
        if(u == null) {
            return Json.format(1, "获取优惠券失败，用户不存在");
        }
        
        List<Voucher> vList = uS.findVoucherByUserId(userId);
        return Json.format(0, "获取优惠券成功", vList);
    }
    
    @RequestMapping(value = "/wxtakein", method=RequestMethod.GET)
    public String wxtakein(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, 
            @RequestParam("nonce") int nonce, @RequestParam("echostr") String echostr) {
        String token = "beehive";
        List<String> list = new ArrayList<String>();
        list.add(timestamp);
        list.add(""+nonce);
        list.add(token);
        Collections.sort(list);
        String str = list.get(0) + list.get(1) + list.get(2);
        if(signature.equals(Encrypt.SHA1(str))) {
            return echostr;
        }
        else {
            return "";
        }
    }
}
